<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <el-tree
          :data="tree"
          @node-click="handleNodeClick"
          :highlight-current="true"
          :default-expand-all="true"
          :expand-on-click-node="false"
          empty-text="数据正在加载中..."
        ></el-tree>
      </el-col>

      <el-col :span="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="showSearch">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
              <el-form-item label="学生姓名" prop="studentName">
                <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>

              <el-form-item label="学籍号" prop="studentCode">
                <el-input v-model="queryParams.studentCode" placeholder="请输入学籍号" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>

              <el-form-item label="民族" prop="nation">
                <el-select v-model="queryParams.nation" placeholder="请选择民族" clearable>
                  <el-option v-for="dict in nation" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['school:student:add']">新增 </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain icon="upload" @click="handledBatchUpload" v-hasPermi="['school:student:add']">批量导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['school:student:edit']"
                  >修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['school:student:remove']"
                  >删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['school:student:export']">导出 </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
          </template>

          <el-table
            v-loading="loading"
            :data="studentList"
            @selection-change="handleSelectionChange"
            @header-click="handleCellMouseEnter"
            v-bind:border="showborder"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="学生姓名" align="center" prop="studentName" v-if="columns[0].visible" />
            <el-table-column label="学号" align="center" prop="studentNumber" v-if="columns[1].visible" />
            <el-table-column label="学籍号" align="center" prop="studentCode" v-if="columns[2].visible" />
            <el-table-column label="性别" align="center" prop="sex" v-if="columns[3].visible">
              <template #default="scope">
                <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
              </template>
            </el-table-column>
            <el-table-column label="头像" align="center" prop="headSculptureId" width="100" v-if="columns[4].visible">
              <template #default="scope">
                <image-preview :src="scope.row.headSculptureId" :width="50" :height="50" />
              </template>
            </el-table-column>
            <el-table-column label="在读状态" align="center" prop="studentStatus" v-if="columns[5].visible">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.studentStatus" />
              </template>
            </el-table-column>
            <el-table-column label="民族" align="center" prop="nation" v-if="columns[6].visible">
              <template #default="scope">
                <dict-tag :options="nation" :value="scope.row.nation" />
              </template>
            </el-table-column>
            <el-table-column label="居住地址" align="center" prop="address" v-if="columns[7].visible" />

            <el-table-column label="所属班级" align="center" prop="className" v-if="columns[11].visible" />
            <el-table-column label="所属校区" align="center" prop="campusName" v-if="columns[12].visible" />
            <el-table-column label="联系电话" align="center" prop="contact" v-if="columns[13].visible" />
            <el-table-column label="维护家长信息" align="center" prop="parentInformation">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdateParents(scope.row)" v-hasPermi="['school:student:edit']"></el-button>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" v-if="columns[14].visible" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['school:student:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['school:student:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改学生管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="studentFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <el-row>
          <campus @schoolCampus="handleSchoolCampus" :selectValue="form.schoolCampusId"></campus>
          <classes @schoolClasses="handleSchoolClasses" :selectValue="form.classesId" :schoolCampusId="form.schoolCampusId"> </classes>
        </el-row>

        <el-form-item label="照片" prop="headSculptureId">
          <!-- <ImageUpload @update:fileId="handleValueUpdate" :fileId="form.headSculptureId" :logo="true" :limit="1" /> -->
          <image-upload v-model="form.headSculptureId" />
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in sys_user_sex" :key="dict.value" :label="parseInt(dict.value)">{{
                                    dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学号" prop="studentNumber">
              <el-input v-model="form.studentNumber" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="学籍号" prop="studentCode">
              <el-input v-model="form.studentCode" placeholder="请输入学籍号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在读状态" prop="studentStatus">
              <el-radio-group v-model="form.studentStatus">
                <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{dict.label}} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择民族">
                <el-option v-for="dict in nation" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="籍贯">
              <el-cascader
                style="width: 300px"
                v-model="form.nativePlace"
                :options="options"
                :props="{ value: 'label', label: 'label', expandTrigger: 'hover' }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居住地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入居住地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" :autosize="{ minRows: 5, maxRows: 5 }" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <ExcelUpload
      @upload-success="handleUpladeResult"
      @upload-cancel="handleCancel"
      :title="title"
      :objectName="objectName"
      :templatePath="templatePath"
      :contentType="contentType"
      v-model="batchImport"
      :uploadPath="uploadPath"
      :size="10"
    ></ExcelUpload>

    <el-dialog :title="title" v-model="parentInfoOpen" append-to-body>
      <el-form ref="studentParent" :model="form" :rules="rules" label-width="80px">
        <div v-for="(item, index) in parents_list" :key="index">
          <el-row @mouseover="showDeleteButton = true" @mouseleave="showDeleteButton = false">
            <el-col :span="1">
              <el-button v-if="showDeleteButton && index != 0" @click="deleteMessage(index)" type="danger" :icon="Delete" circle />
            </el-col>

            <el-col :span="5">
              <el-form-item label="关系" prop="relationShip">
                <el-select v-model="item.relationShip" placeholder="请选择关系" @change="changeselect" clearable>
                  <el-option v-for=" p in parentsType" :key="p.id" :label="p.label" :value="p.label" :disabled="p.selected"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="家长姓名" prop="parentName">
                <el-input v-model="item.parentName" placeholder="请输入家长姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" :prop="item.telphone">
                <el-input v-model="item.telphone" placeholder="请输入家长手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职业" :prop="item.position">
                <el-input v-model="item.position" placeholder="请输入家长职业" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" @click="addMoreParent">+家长信息</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" @click="submitParentForm">确 定</el-button>
              <el-button @click="addparentscancel">取 消</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Student" lang="ts">
import {
    listStudent,
    getStudent,
    delStudent,
    addStudent,
    updateStudent,
    getStudentParents,
    addparents
} from '@/api/school/student';
import {
        StudentVO,
        StudentQuery,
        StudentForm
} from '@/api/school/student/types';

import { getSchoolClassesTreeNode } from "@/api/school/classes";
import { ClassesVO } from '@/api/school/classes/types';
import { regionData } from 'element-china-area-data'
import { Delete } from '@element-plus/icons-vue'
import campus from '@/components/campus/index.vue';
import classes from '@/components/classes/index.vue';
import ExcelUpload from '@/components/ExcelUpload/index.vue';

import { isphone } from '@/utils/validate';

const { proxy } = getCurrentInstance();
    const { sys_yes_no, sys_user_sex, nation } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_user_sex', 'nation'));


const showDeleteButton = ref(false)
const studentList = ref<StudentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formLabelWidth = '120px';
const showborder = ref(false)

const tree = ref<ClassesVO[]>([])
const options = ref(regionData);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();

//excel导入相关
const batchImport = ref(false);
// const bucketName = ref("templates")
const objectName = ref("学生信息导入模板.xls")
const templatePath = ref("school/student/importTemplate");
const contentType = ref("application/octet-stream")
const uploadPath = ref("school/student/upload");



const studentId = ref("");
const schoolCampusId = ref("");
const studentParentName = ref("");
const title = ref("");
const parentInfoOpen = ref(false)


const parents_list = ref([{
    relationShip: '',
    parentName: '',
    telphone: '',
    position: ''
}])



const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: StudentForm = {
                    studentId: undefined,
                    studentName: undefined,
                    studentNumber: undefined,
                    studentCode: undefined,
                    sex: undefined,
                    headSculptureId: undefined,
                    studentStatus: undefined,
                    nation: undefined,
                    address: undefined,
                    province: undefined,
                    city: undefined,
                    districts: undefined,
                    classesId: undefined,
                    schoolCampusId: undefined,
                    contact: undefined,
                    remark: undefined
}
const data = reactive<PageData<StudentForm, StudentQuery>>({
    form: {...initFormData},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
                        studentName: undefined,
                        studentNumber: undefined,
                        studentCode: undefined,
                        sex: undefined,
                        headSculptureId: undefined,
                        studentStatus: undefined,
                        nation: undefined,
                        address: undefined,
                        province: undefined,
                        city: undefined,
                        districts: undefined,
                        classesId: undefined,
                        schoolCampusId: undefined,
                        contact: undefined,
        params: {
        }
    },
    rules: {

                        studentName: [
                        {
                            required: true, message: "学生姓名不能为空", trigger: "blur" }
                    ],
                        studentNumber: [
                        {
                            required: true, message: "学号不能为空", trigger: "blur" }
                    ],
                        studentCode: [
                        {
                            required: true, message: "学籍号不能为空", trigger: "blur" }
                    ],
                        sex: [
                        {
                            required: true, message: "性别不能为空", trigger: "change" }
                    ],
                        studentStatus: [
                        {
                            required: true, message: "在读状态不能为空", trigger: "change" }
                    ],

                        nation: [
                        {
                            required: true, message: "民族不能为空", trigger: "change" }
                    ],
                        address: [
                        {
                            required: true, message: "居住地址不能为空", trigger: "blur" }
                    ],
                        classesId: [
                        {
                            required: true, message: "所属班级不能为空", trigger: "blur" }
                    ],
                        schoolCampusId: [
                        {
                            required: true, message: "所属校区不能为空", trigger: "blur" }
                    ],
                        contact: [
                        {
                            required: true, message: "联系电话不能为空", trigger: "blur" }
                    ]
    }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询学生管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listStudent(queryParams.value);
        studentList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
        studentFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentVO[]) => {
    ids.value = selection.map(item => item.studentId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加学生管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentVO) => {
    reset();
    const _studentId = row?.studentId || ids.value[0]
    const res = await getStudent(_studentId);
    Object.assign(form.value, res.data);
          let array = [];
        array.push(res.data.province)
        array.push(res.data.city)
        array.push(res.data.districts)
        data.form.nativePlace = array
    dialog.visible = true;
    dialog.title = "修改学生管理";
}


/** 提交按钮 */
const submitForm = () => {
        studentFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.studentId) {
                await updateStudent(form.value).finally(() =>  buttonLoading.value = false);
            } else {
                await addStudent(form.value).finally(() =>  buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: StudentVO) => {
    const _studentIds = row?.studentId || ids.value;
    await proxy?.$modal.confirm('是否确认删除学生管理编号为"' + _studentIds + '"的数据项？').finally(() => loading.value = false);
    await delStudent(_studentIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download('school/student/export', {
        ...queryParams.value
    }, `student_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
    getList();
});


//家长管理
const parentsType = ref([
    {
        id: 0,
        label: '爸爸',
        selected: false
    },
    {
        id: 1,
        label: '妈妈',
        selected: false
    },
    {
        id: 2,
        label: '爷爷',
        selected: false
    },
    {
        id: 3,
        label: '奶奶',
        selected: false
    },
    {
        id: 4,
        label: '外公',
        selected: false
    },
    {
        id: 5,
        label: '外婆',
        selected: false
    },
    {
        id: 6,
        label: '其他',
    }
])


/** 列信息 */
const columns = ref([
            {key: 0, label: `学生姓名`, visible: true},
            {key: 1, label: `学号`, visible: true},
            {key: 2, label: `学籍号`, visible: true},
            {key: 3, label: `性别`, visible: true},
            {key: 4, label: `头像`, visible: true},
            {key: 5, label: `在读状态`, visible: true},
            {key: 6, label: `民族`, visible: true},
            {key: 7, label: `居住地址`, visible: true},
            {key: 8, label: `省`, visible: true},
            {key: 9, label: `市`, visible: true},
            {key: 10, label: `区`, visible: true},
            {key: 11, label: `所属班级`, visible: true},
            {key: 12, label: `所属校区`, visible: true},
            {key: 13, label: `联系电话`, visible: true},
            {key: 14, label: `备注`, visible: true},
]);


function handleCellMouseEnter() {
    showborder.value = !showborder.value;
}

function schoolClassesTreeNode() {
    loading.value = true;
    getSchoolClassesTreeNode().then(response => {
      console.log(response);
        tree.value = response.data;
        loading.value = false;
    });


}
/**
 * 点击树返回树的数据
 * @param {} data
 */
function handleNodeClick(data:any) {
    if (data.schoolId == null) {
        console.log("handleNodeClick",data)
        queryParams.value = data;
        getList();
    }
}

//点击维护家长信息按钮，加载学生数据
function handleUpdateParents(row:any) {
  console.log("handleUpdateParents",row)

    const _id = row.studentId || ids.value
    studentId.value = _id;
    studentParentName.value = row.studentName
    schoolCampusId.value = row.schoolCampusId;
    parentInfoOpen.value = true;
    // parents.value.push(size.value)
    title.value = "家长信息管理";

    parents_list.value = [{
        relationShip: '',
        parentName: studentParentName.value + "的家长",
        telphone: '',
        position: ''
    }]

    getStudentParents(_id).then(response => {
        if (response.data.studentParents != "") {
            parents_list.value = response.data.studentParents
        }
        changeselect();

    });


}


function changeselect() {


    for (let a in parents_list.value) {
        if (parents_list.value[a].relationShip != "") {
            parents_list.value[a].parentName = studentParentName.value + "的" + parents_list.value[a].relationShip;
        }
    }
    parentsType.value.forEach(item => {
        item.selected = false;
        for (let a in parents_list.value) {
            if (item.label == parents_list.value[a].relationShip && item.label != '其他') {
                item.selected = true;
            }
        }
    });
}


//excel导入相关
function handleCancel(value: boolean) {
    batchImport.value = value;
}
function handleUpladeResult(value: any) {
    if (value) {
        batchImport.value = false;
        getList();
    }
}

/**
 * 从 campus组件中获取校区
 * @param {*} value
 */
function handleSchoolCampus(value: string|number|undefined) {
    data.form.schoolCampusId = value;
    // data.form.classesId = null;
    //根据校区获取班级信息
}


//选择班级
function handleSchoolClasses(value: string|number|undefined) {
    data.form.classesId = value;
}


//头像上传
function handleValueUpdate(value: string|number|undefined) {
    data.form.headSculptureId = value;
}

function handledBatchUpload() {
    title.value = "批量导入学生";
    batchImport.value = true;
}


function addMoreParent() {

    if(parents_list.value.length>=9){
        proxy.$modal.msgError("添加绑定家长数量过多！");
        return;
    }

    parents_list.value.push({
        relationShip: '',
        parentName: studentParentName.value + "的家长",
        telphone: '',
        position: ''
    })

}


/**
 * 提交家长信息
 */
function submitParentForm() {
    proxy.$refs["studentParent"].validate(() => {
        for (let item in parents_list.value) {
            let relationShip = parents_list.value[item].relationShip;
            let parentName = parents_list.value[item].parentName;
            let telphone = parents_list.value[item].telphone;
            let position = parents_list.value[item].position;
            let line = Number(item) + 1;
            if (relationShip == null || relationShip == "" || relationShip == undefined) {
                proxy.$modal.msgError("第" + line + "行请选择与学生关系！");
                return;
            }
            if (parentName == null || parentName == "" || parentName == undefined) {
                proxy.$modal.msgError("第" + line + "行家长姓名不能为空！");
                return;
            }

            if (telphone == null || telphone == "" || telphone == undefined) {
                proxy.$modal.msgError("第" + line + "行家长手机号不能为空！");
                return;
            }
            if (!isphone(telphone)) {
                proxy.$modal.msgError("第" + line + "行请输入正确的手机号！");
                return;
            }


            if (position == null || position == "" || position == undefined) {
                proxy.$modal.msgError("第" + line + "行请输入家长职业！");
                return;
            }

        }

        data.form.studentParents = parents_list.value;
        data.form.studentId = studentId.value;
        data.form.schoolCampusId = schoolCampusId.value;

        addparents(form.value).then(() => {
            proxy.$modal.msgSuccess("新增成功");
            parentInfoOpen.value = false;
            getList();
        });



    });
}

function addparentscancel() {
    parentInfoOpen.value = false;
}


function deleteMessage(index: number) {
    parents_list.value.splice(index, 1)
    changeselect();
}

schoolClassesTreeNode()
</script>
